﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Base.ModuleBase.Attachs
{
    public class WindowDragMoveAttach
    {
        public static readonly DependencyProperty IsMouseMoveProperty =
            DependencyProperty.RegisterAttached("IsMouseMove"
            , typeof(bool)
            , typeof(WindowDragMoveAttach)
            , new PropertyMetadata(IsMouseMovePropertyChanged));

        public static bool GetIsMouseMove(DependencyObject owner)
        {
            return (bool)owner.GetValue(IsMouseMoveProperty);
        }

        public static void SetIsMouseMove(DependencyObject owner, bool value)
        {
            owner.SetValue(IsMouseMoveProperty, value);
        }

        private static void IsMouseMovePropertyChanged(DependencyObject hostControl, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is false)
                return;
            if (hostControl is UserControl user)
            {
                user.Loaded -= User_Loaded;
                user.Loaded += User_Loaded;
            }
            else if (hostControl is Window window)
            {
                window.MouseLeftButtonDown -= Window_MouseLeftButtonDown;
                window.MouseLeftButtonDown += Window_MouseLeftButtonDown;
            }
        }

        private static void User_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is UserControl user)
            {
                var tempWindow = user.GetParentObject<Window>();
                if (tempWindow is null)
                    return;
                tempWindow.MouseLeftButtonDown -= Window_MouseLeftButtonDown;
                tempWindow.MouseLeftButtonDown += Window_MouseLeftButtonDown;
            }
        }

        private static void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is Window window)
            {
                Point point = e.GetPosition(window);
                var height = (double)Application.Current.Resources["WindowHeaderHeight"];
                if (point.Y > 0 && point.Y < height)
                {
                    window.DragMove();
                }
            }
        }

        public static readonly DependencyProperty WindowTitleProperty =
            DependencyProperty.RegisterAttached("WindowTitle"
            , typeof(string)
            , typeof(WindowDragMoveAttach));

        public static string GetWindowTitle(DependencyObject owner)
        {
            return (string)owner.GetValue(WindowTitleProperty);
        }

        public static void SetWindowTitle(DependencyObject owner, string value)
        {
            owner.SetValue(WindowTitleProperty, value);
        }
    }
}
